import React from 'react';
import {
  Form,
  Modal,
  Card,
  DatePicker,
  Input,
  InputNumber,
  Radio,
  Button,
  Table,
  Row,
  Col
} from 'antd';
import { purchaseType, purchaseType4Special } from 'utils/enumConfig';
import { validateMobile } from 'utils/utils';
import moment from 'moment'

const FormItem = Form.Item
const RadioGroup = Radio.Group
const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 14
  }
}
const customPanelStyle = {
  marginBottom: 24
};
const PayOrderPublishModal = ({
  dispatch,
  toChangeOrder,
  onOk,
  onAddMaterielItem,
  isUpdate,
  isLoading,
  currentPayOrder,
  onDeleteMaterielItem,
  onMaterielItemChange,
  isPushOmsModel,
  currentSystemProperty,
  commodities,
  currentOrderDetail,
  form: {
    getFieldDecorator,
    validateFieldsAndScroll
  },
  ...updateModalProps
}) => {
  const handleSubmit = (handleType) => {
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (handleType === "CONFIRM_SUBMIT" && isPushOmsModel) {
          values.contractSignedAt = values.contractSignedAt.valueOf();
          values.contractInstalledAt = values.contractInstalledAt.valueOf();
          _.each(currentPayOrder.materielItems, (item) => {
            delete item.index;
          });
          values.goodsSnapshots = commodities;
          values.productType = currentPayOrder.productType;
          values.version = currentPayOrder.version;
          values.payOrderId = currentPayOrder.id
          delete values.quoteAttachment;
          if (values.goodsSnapshots.every((item, index, array) => {
            return _.isEmpty(item.purchaseType)
          }) || values.goodsSnapshots.length !== currentPayOrder.goodsSnapshots.length) {
            Modal.error({
              title: '错误',
              content: '请给所有物料都选上一种采购方式',
            });
            return;
          }
          dispatch({
            type: "updateContractOrder/complete",
            payload: values
          })
          dispatch({
            type: 'updateContractOrder/getOrderDetail',
            payload: {
              orderId: currentOrderDetail.id
            }
          })
          dispatch({
            type: 'updateContractOrder/listAllPayOrder', payload: currentOrderDetail.id
          })
        } else {
          dispatch({
            type: "updateContractOrder/toTenant",
            payload: {
              isPushOms: isPushOmsModel,
            }
          })
          dispatch({
            type: 'updateContractOrder/getOrderDetail',
            payload: {
              orderId: currentOrderDetail.id
            }
          })
          dispatch({
            type: 'updateContractOrder/listAllPayOrder', payload: currentOrderDetail.id
          })
        }
      }
    });
  };
  let flag = 0;

  const checkPurchaseType = () => {
    const purchaseList = currentSystemProperty.purchaseEntityList;

    if (purchaseList.length >= 2) {
      purchaseList.foreach((element) => {
        if (element.purchaseType === 'SELF_OPERATED' || element.purchaseType === 'TAKE_PURCHASE') {
          flag++;
        }
      })
    }

  }

  const paramsColumns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (<span>{text}</span>)
    }, {
      title: '物料',
      dataIndex: 'fullMaterielName',
      key: 'fullMaterielName',
      render: (text, record) => (<span>{text}</span>)
    }
    , {
      title: '商品图片',
      dataIndex: 'coverPath',
      key: 'coverPath',
      render: (text, record) => <img alt="" src={text} height={60} width={60} />
    }
    , {
      title: '商品数量',
      dataIndex: 'number',
      key: 'number',
    }
    ,
    {
      title: '操作',
      width: 300,
      render: (text, record) => {
        return (
          <div>
            <RadioGroup onChange={(e) => {
              dispatch({
                type: 'updateContractOrder/setPurchaseTypeToPayOrder',
                payload: {
                  record: record,
                  purchaseType: e.target.value
                }
              })
            }}>
              {currentSystemProperty.purchaseEntityList.map(element => {
                return <Radio value={element.purchaseType} checked={currentSystemProperty.purchaseEntityList.length === 1}
                >
                  {currentSystemProperty.purchaseTypeCheck ?
                    purchaseType[element.purchaseType] : purchaseType4Special[element.purchaseType]
                  }

                </Radio>
              })}
            </RadioGroup>
          </div >
        );
      },
    }
  ];
  const listProps = {
    dataSource: currentPayOrder.goodsSnapshots,
    pagination: false
  }

  const getParamsColumns = (option) => {
    if (option) {
      paramsColumns.pop();
    }
    return paramsColumns;
  }

  return (
    <Modal {...updateModalProps} loading={isLoading}>
      <Form onSubmit={handleSubmit} hideRequiredMark>
        {
          <Card type="inner" title="下单信息" style={customPanelStyle}>
            <Row>
              <Col span={12}>
                <FormItem {...formItemLayout} label="合同号">
                  {getFieldDecorator('contractNum', {
                    rules: [
                      {
                        required: true,
                        message: '请输入合同号',
                        whitespace: true
                      },
                    ],
                    initialValue: currentPayOrder.orderNum
                  })(<Input disabled placeholder="请输入合同号" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="合同签订时间">
                  {getFieldDecorator('contractSignedAt', {
                    rules: [
                      {
                        required: true,
                        message: '请选择合同下单时间',
                        type: 'object',
                      },
                    ],
                    initialValue: moment(currentPayOrder.orderContractAt)
                  })(
                    <DatePicker style={{ width: '100%' }} />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="合同到货时间">
                  {getFieldDecorator('contractInstalledAt', {
                    rules: [
                      {
                        required: true,
                        message: '请选择合同到货时间',
                        type: 'object',
                      },
                    ],
                    initialValue: moment(currentPayOrder.installContractAt)
                  })(
                    <DatePicker style={{ width: '100%' }} />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="合同金额">
                  {getFieldDecorator('contractAmount', {
                    rules: [
                      {
                        required: true,
                        message: '请输入合同金额'
                      },
                    ],
                    initialValue: currentPayOrder.amountInChannelPrice
                  })(<InputNumber disabled style={{ width: "100%" }} placeholder="请输入合同金额" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="收货人姓名">
                  {getFieldDecorator('receiptUserName', {
                    rules: [
                      {
                        required: true,
                        message: '请输入收货人姓名',
                        whitespace: true,
                      },
                    ],
                    initialValue: currentPayOrder.consigneeName
                  })(<Input disabled placeholder="请输入收货人姓名" />)}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout} label="收货人手机号">
                  {getFieldDecorator('receiptUserPhoneNum', {
                    rules: [
                      {
                        required: true,
                        message: '请输入收货人手机号',
                        whitespace: true
                      }, {
                        validator: validateMobile
                      }
                    ],
                    initialValue: currentPayOrder.consigneePhoneNum
                  })(<Input disabled placeholder="请输入收货人手机号" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="收货地址">
                  {getFieldDecorator('receiptAddress', {
                    rules: [
                      {
                        required: true,
                        message: '请输入收货地址',
                        whitespace: true
                      },
                    ],
                    initialValue: currentPayOrder.consigneeAddress
                  })(<Input disabled placeholder="请输入收货地址" />)}
                </FormItem>
                {isPushOmsModel && <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator('memo', {
                    initialValue: currentPayOrder.description
                  })(<Input placeholder="请输入备注" />)}
                </FormItem>}
              </Col>
            </Row>
          </Card>}
        {isPushOmsModel && <Card type="inner" title="成品列表" style={customPanelStyle} >
          {/* {!currentPayOrder.isFromThirdPart && <Button onClick={e => onAddMaterielItem()} style={{ marginBottom: 10 }} >添加物料</Button>} */}
          <Table
            columns={getParamsColumns(currentPayOrder.isFromThirdPart)}
            size="middle"
            rowKey={record => record.code}
            {...listProps} />
        </Card>}
        <FormItem
          style={{ marginTop: 30 }}
          wrapperCol={{ span: 6, offset: 22 }}>
          {currentSystemProperty.purchaseEntityList && currentSystemProperty.purchaseEntityList.length !== 1 && <Button type="primary" onClick={() => handleSubmit("CONFIRM_SUBMIT")} style={{ marginRight: 10 }} loading={isLoading}>
            确认下单
          </Button>}
        </FormItem>
      </Form>
    </Modal>
  )
}

export default Form.create()(PayOrderPublishModal);
